package com.aiyi.education.user.service.impl;


import cn.hutool.crypto.digest.BCrypt;
import com.aiyi.education.entity.KsUser;
import com.aiyi.education.entity.KsUserWithBLOBs;
import com.aiyi.education.entity.admin.KsAdmin;
import com.aiyi.education.mapper.KsUserMapper;
import com.aiyi.education.user.service.IKsUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.education.base.Constant;
import com.education.base.ErrorReturnConstant;
import com.education.base.PublicResultConstant;
import com.education.exception.BusinessException;
import com.education.util.ComUtil;
import com.education.util.GenerationSequenceUtil;
import com.education.util.JWTUtil;
import com.education.util.StringUtil;
import com.education.util.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author renyong
 * @since 2020-04-22
 */
@Service
public class KsUserServiceImpl extends ServiceImpl<KsUserMapper, KsUserWithBLOBs> implements IKsUserService {

    @Autowired
    private KsUserMapper ksUserMapper;

    @Override
    public void saveSysUser(KsUser ksUser) {
        ksUserMapper.saveSysUser(ksUser);
    }



    @Override
    public IPage<KsUser> getUsersPage(Page<KsUser> page, JSONObject jsonObject) {
        KsUser ksUser= JSON.parseObject(jsonObject.toJSONString(), KsUser.class);
        IPage<KsUser> pages=ksUserMapper.getUserPage(page,ksUser);
        return pages;
    }

    @Override
    public Result<?> resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        return null;
    }

    @Override
    public Result<?> changePassword(KsUser KsUser) {
        return null;
    }

    @Override
    public Integer deleteUser(KsUserWithBLOBs ksUser) {
        return ksUserMapper.deleteById(ksUser.getUserId());
    }

    @Override
    public boolean deleteBatchUsers(String userIds) {
        ksUserMapper.deleteBatchIds(Arrays.asList(userIds.split(",")));
        return false;
    }

    @Override
    public KsUser getUserByParames(String usernName) {
        KsUser ksUser=new KsUser();
        ksUser.setUserName(usernName);
        List<KsUser> list=ksUserMapper.getUserListByParams(ksUser);
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public void addUserWithRole(KsUser user, String roles) {

    }

    @Override
    public void editUserWithRole(KsUser user, String roles) {

    }

    @Override
    public List<String> getRole(String username) {
        return null;
    }

    @Override
    public IPage<KsUser> getUserByDepId(Page<KsUser> page, String departId, String username) {
        return null;
    }

    @Override
    public IPage<KsUser> getUserByDepIds(Page<KsUser> page, List<String> departIds, String username) {
        return null;
    }

    @Override
    public Map<String, String> getDepNamesByUserIds(List<String> userIds) {
        return null;
    }

    @Override
    public IPage<KsUser> getUserByDepartIdAndQueryWrapper(Page<KsUser> page, String departId, QueryWrapper<KsUser> queryWrapper) {
        return null;
    }

    @Override
    public IPage<KsUser> getUserByRoleId(Page<KsUser> page, String roleId, String username) {
        return null;
    }

    @Override
    public Set<String> getUserRolesSet(String username) {
        return null;
    }

    @Override
    public Set<String> getUserPermissionsSet(String username) {
        return null;
    }

    @Override
    public void updateUserDepart(String username, String orgCode) {

    }

    @Override
    public KsUser getUserByPhone(String phone) {
        return null;
    }

    @Override
    public KsUser getUserByEmail(String email) {
        return null;
    }

    @Override
    public void addUserWithDepart(KsUser user, String selectedParts) {

    }

    @Override
    public void editUserWithDepart(KsUser user, String departs) {

    }

    @Override
    public Result checkUserIsEffective(KsUser KsUser) {
        return null;
    }

    @Override
    public List<KsUser> queryLogicDeleted() {
        return null;
    }

    @Override
    public List<KsUser> queryLogicDeleted(LambdaQueryWrapper<KsUser> wrapper) {
        return null;
    }

    @Override
    public boolean revertLogicDeleted(List<String> userIds, KsUser updateEntity) {
        return false;
    }

    @Override
    public boolean removeLogicDeleted(List<String> userIds) {
        return false;
    }

    @Override
    public KsUserWithBLOBs getUserByUserNo(String userNo) {
        return ksUserMapper.selectById(userNo);
    }

    @Override
    public Map<String, Object> checkLoginAccountAndPasswd(JSONObject requestJson) throws Exception {
        //由于 @ValidationParam注解已经验证过mobile和passWord参数，所以可以直接get使用没毛病。
        String userAccount = requestJson.getString("userAccount");
        //手机号格式验证
        /*if(!StringUtil.checkMobileNumber(mobile)){
            throw new BusinessException(PublicResultConstant.MOBILE_ERROR);
        }*/
        if (StringUtils.isEmpty(userAccount)||StringUtils.isEmpty(requestJson.getString("password"))) {
            throw new BusinessException(ErrorReturnConstant.ACCOUNT_OR_PASSWORD_CANNOT_BE_EMPTY);
        }

        KsUserWithBLOBs user = this.userAccountMatching(requestJson);
        if (ComUtil.isEmpty(user) || !BCrypt.checkpw(requestJson.getString("password"), user.getPassword())) {
            throw new BusinessException(PublicResultConstant.INVALID_USERNAME_PASSWORD);
        }
        //测试websocket用户登录给管理员发送消息的例子  前端代码参考父目录下WebSocketDemo.html
//        noticeService.insertByThemeNo("themeNo-cwr3fsxf233edasdfcf2s3","13888888888");
//        MyWebSocketService.sendMessageTo(JSONObject.toJSONString(user),"13888888888");

        return this.getLoginUserAndMenuInfo(user);
    }

    @Override
    public KsUserWithBLOBs checkAndRegisterUser(JSONObject requestJson) throws Exception {
        //可直接转为java对象,简化操作,不用再set一个个属性
        KsUserWithBLOBs userRegister = requestJson.toJavaObject(KsUserWithBLOBs.class);
        if(!StringUtil.checkMobileNumber(userRegister.getMobile())){
            throw new BusinessException(PublicResultConstant.MOBILE_ERROR);
        }
        if (!userRegister.getPassword().equals(requestJson.getString("rePassword"))) {
            throw new BusinessException(PublicResultConstant.INVALID_RE_PASSWORD);
        }
        /*List<SmsVerify> smsVerifies = smsVerifyService.getByMobileAndCaptchaAndType(userRegister.getMobile(),
                requestJson.getString("captcha"), SmsSendUtil.SMSType.getType(SmsSendUtil.SMSType.REG.name()));
        if(ComUtil.isEmpty(smsVerifies)){
            throw new BusinessException(PublicResultConstant.VERIFY_PARAM_ERROR);
        }
        //验证码是否过期
        if(SmsSendUtil.isCaptchaPassTime(smsVerifies.get(0).getCreateTime())){
            throw new BusinessException(PublicResultConstant.VERIFY_PARAM_PASS);
        }*/
        userRegister.setPassword(BCrypt.hashpw(requestJson.getString("password"), BCrypt.gensalt()));
        //默认注册普通用户
        return this.register(userRegister, Constant.UserLoginType.USER);
    }


    @Override
    public Map<String, Object> getLoginUserAndMenuInfo(KsUserWithBLOBs user) {
        Map<String, Object> result = new HashMap<>();
        // BaseUserToRole baseUserToRole = baseUserToRoleService.selectByUserNo(user.getUserNo());
        user.setToken(JWTUtil.sign(user.getUserId().toString(), user.getPassword(),Constant.UserLoginType.USER));
        //更新最后登录时间
        KsUserWithBLOBs updateUser = new KsUserWithBLOBs();
        updateUser.setUserId(user.getUserId());
        updateUser.setLastLoginTime(new Date());
        this.updateById(updateUser);
        //过滤字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        filter.getExcludes().add("password");
        filter.getExcludes().add("rndPassword");
        filter.getExcludes().add("loginTimes");
        filter.getExcludes().add("checkNum");
        String resultJson = JSONObject.toJSONString(user,filter);
        user = JSON.parseObject(resultJson,KsUserWithBLOBs.class);
        result.put("user",user);
        /*List<BaseMenu> buttonList = new ArrayList<BaseMenu>();
        List<BaseMenu> retMenuList = new ArrayList<BaseMenu>();*/

        //根据角色主键查询启用的菜单权限
        // List<BaseMenu> menuList = baseMenuService.findBaseMenuByRoleCode(baseUserToRole.getRoleCode());
       /*
        List<BaseMenu> retMenuList = baseMenuService.treeBaseMenuList(Constant.ROOT_MENU, menuList);
        for (BaseMenu buttonMenu : menuList) {
            if(buttonMenu.getMenuType() == Constant.TYPE_BUTTON){
                buttonList.add(buttonMenu);
            }
        }
        */
        /*result.put("menuList",retMenuList);
        result.put("buttonList",buttonList);*/
        return result;
    }

    private KsUserWithBLOBs register(KsUserWithBLOBs user, String  roleCode) {
        //user.setUserId(GenerationSequenceUtil.generateUUID("user"));
        user.setJoinDate(new Date());
        boolean result = this.save(user);
        /*if (result) {
            BaseUserToRole userToRole  = BaseUserToRole.builder().userNo(user.getUserNo()).roleCode(roleCode).build();
            baseUserToRoleService.insert(userToRole);
        }*/
        return user;
    }

    private KsUserWithBLOBs userAccountMatching(JSONObject requestJson){
        QueryWrapper wrapper = new QueryWrapper();
        StringBuffer existsSql = new StringBuffer("select user_id from ks_user where ");
        if (StringUtils.isNotEmpty(requestJson.getString("userAccount"))){
            existsSql.append("user_id = \'"+ requestJson.getString("userAccount")+"\'");
            existsSql.append(" or mobile = \'"+requestJson.getString("userAccount")+"\'");
            existsSql.append(" or user_name = \'"+requestJson.getString("userAccount")+"\'");
        }
        wrapper.exists(existsSql.toString());
        KsUserWithBLOBs user = this.getOne(wrapper);
        return user;
    }
}
